<template>
  <ele-page>
    <search @search="reload" />
    <ele-card :body-style="{ paddingTop: '8px' }">
      <!-- 表格 -->
      <ele-pro-table
        ref="tableRef"
        row-key="roleId"
        :columns="columns"
        :datasource="datasource"
        :show-overflow-tooltip="true"
        v-model:selections="selections"
        highlight-current-row
        :where="defaultWhere"
        border
        show-summary
        :summary-method="getSummaries"
      >
        <template #toolbar="{}">
          <!-- <el-button type="success" @click="exportExcel" :icon="DocumentCopy">
            导出表格
          </el-button> -->
          <span style="margin-left: 8px">总计：{{ totalAmount }}元</span>
        </template>
        <template #status="{ row }">
          <el-tag :type="statusType(row.status)">
            {{ statusText(row.status) }}
          </el-tag>
        </template>
        <template #user_name="{ row }">
          <span class="pointer blue" @click="showStudentDetail(row)">
            {{ row.realname }}
          </span>
        </template>
        <template #goods_price="{ row }">
          <span class="pointer blue" @click="openPayRecord(row)">
            {{ row.goods_price }}
          </span>
        </template>
        <template #action="{ row }">
          <el-button-group>
            <el-button type="success" size="small" @click="passRefund(row)"
              >通过</el-button
            >
            <el-button type="danger" size="small" @click="openReject(row)"
              >拒绝</el-button
            >
          </el-button-group>
        </template>
      </ele-pro-table>
    </ele-card>
    <!-- 学生详情 -->
    <detail v-model="showDetail" :student-id="currentId" @done="reload" />
    <reject v-model="showReject" :data="current" @done="reload" />
  </ele-page>
</template>

<script setup>
  import { ref, computed } from 'vue';
  import { pageMallTradeRefund, passMallTradeRefund } from '@/api/mall';
  import { EleMessage } from 'ele-admin-plus/es';
  import { ElMessageBox } from 'element-plus/es';
  import Detail from '@/views/student/components/detail.vue';
  import Reject from './components/reject.vue';
  import Search from './components/search.vue';
  import { accAdd } from '@/utils/my-common';
  /** 表格实例 */
  const tableRef = ref(null);

  const totalAmount = ref(0);

  const statusText = (value) => {
    const cs = {
      0: '待处理',
      '-1': '已拒绝',
      1: '已退款'
    };
    return cs[value];
  };
  const statusType = (state) => {
    const stateMap = {
      0: 'warning',
      '-1': 'danger',
      1: 'success'
    };
    return stateMap[state];
  };

  /** 表格列配置 */
  const columns = computed(() => {
    const cols = [
      {
        prop: 'id',
        label: 'ID',
        width: 100
      },
      {
        slot: 'status',
        label: '状态',
        width: 100
      },
      {
        prop: 'goods_title',
        label: '商品名称'
      },
      {
        slot: 'user_name',
        label: '购买会员',
        width: 100
      },
      {
        prop: 'tel',
        label: '电话',
        width: 130
      },
      {
        prop: 'goods_price',
        label: '购买价格',
        width: 120
      },
      {
        prop: 'buyTime',
        label: '购买时间',
        width: 155
      },
      {
        prop: 'create_time',
        label: '申请退款时间',
        width: 165
      }
    ];
    if (status.value == 0) {
      cols.push({
        slot: 'action',
        label: '操作',
        width: 200
      });
    }
    if (status.value == -1 || status.value == 1) {
      cols.push(
        {
          prop: 'judge_user',
          label: '操作人',
          width: 100
        },
        {
          prop: 'judge_time',
          label: '操作时间',
          width: 170
        }
      );
    }
    if (status.value == -1) {
      cols.push({
        prop: 'refund_reject_reason',
        label: '拒绝原因',
        width: 200
      });
    }
    return cols;
  });

  const status = ref(0);

  /** 表格选中数据 */
  const selections = ref([]);

  /** 表格数据源 */
  const datasource = async ({ page, where, orders, limit }) => {
    const result = await pageMallTradeRefund({
      ...where,
      ...orders,
      page,
      limit
    });
    console.log('result:', result);
    totalAmount.value = result.totalAmount;

    return result;
  };

  const defaultWhere = ref({
    status: '全部',
    create_time: '',
    valid_time: '',
    realname: '',
    tel: '',
    title: ''
  });

  /** 搜索 */
  const reload = (where) => {
    status.value = where ? where.status : 0;
    selections.value = [];
    tableRef.value?.reload?.({ page: 1, where });
  };

  const currentId = ref(0);
  const showDetail = ref(false);
  /** 学生详情 */
  const showStudentDetail = (row) => {
    currentId.value = row.user_id ?? 0;
    showDetail.value = true;
  };

  /** 拒绝退款 */
  const current = ref([]);
  const showReject = ref(false);
  /** 学生详情 */
  const openReject = (row) => {
    current.value = row ?? null;
    showReject.value = true;
  };

  /** 通过退款 */
  const passRefund = (row) => {
    const rows = row == null ? selections.value : [row];
    if (!rows.length) {
      EleMessage.error('请至少选择一条数据');
      return;
    }
    ElMessageBox.confirm(
      '通过“' + rows.map((d) => d.realname).join(', ') + '”的退款申请吗?',
      '系统提示',
      { type: 'warning', draggable: true }
    )
      .then(() => {
        const loading = EleMessage.loading('请求中..');
        const id = row.id;
        const pay_record_id = row.pay_record_id;
        const trade_id = row.trade_id;
        passMallTradeRefund({ id, pay_record_id, trade_id })
          .then((msg) => {
            loading.close();
            EleMessage.success(msg);
            reload();
          })
          .catch((e) => {
            loading.close();
            EleMessage.error('操作成功');
            console.log(e.message);
          });
      })
      .catch(() => {});
  };

  const getSummaries = (param) => {
    const { columns, data } = param;
    const sums = [];
    columns.forEach((column, index) => {
      if (index === 0) {
        sums[index] = '本页统计';
        return;
      }
      const values = data.map((item) => Number(item[column.property]));
      if (index === 5) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!isNaN(value)) {
            return accAdd(prev, curr);
          } else {
            return prev;
          }
        }, 0);
        sums[index] += ' 元';
      } else {
        sums[index] = '/';
      }
    });

    return sums;
  };
</script>

<script>
  export default {
    name: 'SystemRole'
  };
</script>
